<?php

namespace ApiBundle\Controller\V1;

use ApiBundle\Controller\BaseController;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\FOSRestController;
use GamesBundle\Entity\GamesComplain;
use GamesBundle\Entity\User;
use GamesBundle\Entity\UserInvite;
use GamesBundle\Entity\UserProfile;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\View\View;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;


class UserController extends BaseController
{
    /**
     * @author  coffey
     * 获取用户信息
     *
     * @ApiDoc(
     *  resource=true,
     *  description="获取用户信息的接口",
     *  parameters={
     *      {"name"="userToken", "dataType"="string","required"=true, "description"="用户token"},
     *  },
     * )
     * @Rest\POST("/user/getinfo")
     */
    public function getUserAction(Request $request)
    {
        $param['userToken'] = $request->request->get('userToken','');
        if($this->checkParam($param) == false)
        {
            return $this->FinalJson(1);
        }
        $tokenData = $this->checkToken($param['userToken']);
        if(isset($tokenData['code']) && $tokenData['code'] == 1)
        {
            $userInfo   =   $tokenData['userinfo'] ? $tokenData['userinfo'] : array();
            if(!isset($userInfo['userId']) || empty($userInfo['userId']))
            {
                return $this->FinalJson(5,array());
            }
            $tokenData['userinfo']['userToken'] = $param['userToken'];
            return $this->FinalJson(0,$tokenData['userinfo']);
        }
        else
        {
            return $this->FinalJson($tokenData['errcode']);
        }
    }

    /**
     * 用户注册
     *
     * @ApiDoc(
     *  resource=true,
     *  description="用户注册接口，返回用户个人信息",
     *  parameters={
     *      {"name"="username", "dataType"="string","required"=true,"description"="用户名，字母数字 不得超过20位"},
     *      {"name"="password", "dataType"="string","required"=true, "description"="密码"},
     *      {"name"="invcode", "dataType"="string","required"=true,"description"="邀请码"},
     *  },
     * )
     * @Rest\POST("/user/reg")
     */
    public function registerAction(Request $request)
    {
        $param['username'] = $request->request->get('username','');
        $param['password'] = $request->request->get('password','');
        if($this->checkParam($param) == false)
        {
            return $this->FinalJson(1);
        }
        $param['invcode'] = $request->request->get('invcode','');
        $userInfo = $this->getUserRepository()->findOneBy(array('username'=>$param['username']));
        if(!empty($userInfo))
        {
            return new JsonResponse(array('code'=>10,'msg'=>'用户名已存在'));
        }
        $codeInfo = $this->getUserRepository()->findOneBy(array('invCode'=>$param['invcode']));
        $user = new User();
        $user->setUsername($param['username']);
        $password = $param['password'];
        $encoder = $this->container->get('security.encoder_factory')
            ->getEncoder($user)
        ;
        $encoded = $encoder->encodePassword($password, $user->getSalt());
        $user->setPassword($encoded);
        $this->_em()->persist($user);
        $this->_em()->flush($user);
        $user->setInvCode($user->getId());
        $this->_em()->persist($user);
        $this->_em()->flush($user);

        $userProfile = new UserProfile();
        $userProfile->setUserId($user);
        $user->setProfile($userProfile);
        $this->_em()->persist($userProfile);
        $this->_em()->flush($userProfile);
        $this->_em()->persist($user);
        $this->_em()->flush($user);
        $result = $this->getYunXinOper()->createUserIds(md5($user->getUsername()),$user->getUsername());
        $user->setYunxinId($result['info']['accid']);
        $user->setYunxinToken($result['info']['token']);
        $this->_em()->persist($user);
        $this->_em()->flush($user);
        if(!empty($codeInfo))
        {
            $invUser = new UserInvite();
            $invUser->setUserId($user);
            $invUser->setInviterId($codeInfo);
            $invUser->setInviteCode($param['invcode']);
            $this->_em()->persist($invUser);
            $this->_em()->flush($invUser);
        }

        $returnArr = $this->getUserRepository()->loadUserInfo($user->getUsername());
        return $this->FinalJson(0,$returnArr);
    }

    /**
     * 修改密码
     *
     * @ApiDoc(
     *  resource=true,
     *  description="用户修改密码",
     *  parameters={
     *      {"name"="userToken", "dataType"="string","required"=true,"description"="用户token"},
     *      {"name"="oldPassword", "dataType"="string","required"=true,"description"="旧密码"},
     *      {"name"="password", "dataType"="string","required"=true,"description"="密码"},
     *  },
     * )
     * @Rest\POST("/user/changepw")
     */
    public function changePwAction(Request $request)
    {
        $param['userToken'] = $request->request->get('userToken','');
        $param['oldPassword'] = $request->request->get('oldPassword','');
        $param['password'] = $request->request->get('password','');
        if($this->checkParam($param) == false)
        {
            return $this->FinalJson(1);
        }
        $tokenData = $this->checkToken($param['userToken']);
        if(isset($tokenData['code']) && $tokenData['code'] == 1)
        {
            $userInfo   =   $tokenData['userinfo'] ? $tokenData['userinfo'] : array();
            if(!isset($userInfo['userId']) || empty($userInfo['userId']))
            {
                return $this->FinalJson(5,array());
            }
            $userId =   $userInfo['userId'];
            $user = $this->getUserRepository()->find($userId);
        }
        else
        {
            return $this->FinalJson($tokenData['errcode']);
        }
        $passwordStr = $user->getPassword();
        if (password_verify($param['oldPassword'], $passwordStr)) {
            $password = $param['password'];
            $encoder = $this->container->get('security.encoder_factory')
                ->getEncoder($user)
            ;
            $encoded = $encoder->encodePassword($password, $user->getSalt());
            $user->setPassword($encoded);
            $this->_em()->persist($user);
            $this->_em()->flush($user);
            return $this->FinalJson(0);
        }
        return $this->FinalJson(8,$param);
    }

    /**
     * 上传头像
     *
     * @ApiDoc(
     *  resource=true,
     *  description="用户上传头像",
     *  parameters={
     *      {"name"="userToken", "dataType"="string","required"=true,"description"="用户token"},
     *      {"name"="baseHeadImg", "dataType"="string","required"=true,"description"="base64加密图片"},
     *  },
     * )
     * @Rest\POST("/user/uploadheadimg")
     */
    public function uploadHeadImgAction(Request $request)
    {
        $param['userToken'] = $request->request->get('userToken','');
        $param['baseHeadImg'] = $request->request->get('baseHeadImg','');
        $tokenData = $this->checkToken($param['userToken']);
        if(isset($tokenData['code']) && $tokenData['code'] == 1)
        {
            $userInfo   =   $tokenData['userinfo'] ? $tokenData['userinfo'] : array();
            if(!isset($userInfo['userId']) || empty($userInfo['userId']))
            {
                return $this->FinalJson(5,array());
            }
            $userId =   $userInfo['userId'];
            $user = $this->getUserRepository()->find($userId);
        }
        else
        {
            return $this->FinalJson($tokenData['errcode']);
        }

        $upload = $this->container->get('games_upload');
        $result = $upload->baseDecodeImg($param['baseHeadImg']);
        if(!empty($result['code'] == 0))
        {
            $user->setHeadimg($result['filepath']);
            $this->_em()->persist($user);
            $this->_em()->flush($user);
            $info = $this->getUserRepository()->loadUserInfo($user->getUsername());
            return $this->FinalJson(0,$info);
        }
        return $this->FinalJson(1);
    }

    /**
     * 用户反馈建议
     *
     * @ApiDoc(
     *  resource=true,
     *  description="用户反馈建议",
     *  parameters={
     *      {"name"="userToken", "dataType"="string","required"=true,"description"="用户token"},
     *      {"name"="com", "dataType"="string","required"=true,"description"="反馈意见"},
     *  },
     * )
     * @Rest\POST("/user/complain")
     */
    public function complainAction(Request $request)
    {
        $token = $request->request->get('user_token','');
        $param['userToken'] =   $request->request->get('userToken','');
        $param['com'] = $request->request->get('com','');

        if($this->checkParam($param) == false)
        {
            return $this->FinalJson(1);
        }
        $tokenData  =   $this->checkToken($param['userToken']);
        if(isset($tokenData['code']) && $tokenData['code'] == 1)
        {
            $userInfo   =   $tokenData['userinfo'] ? $tokenData['userinfo'] : array();
            if(!isset($userInfo['userId']) || empty($userInfo['userId']))
            {
                return $this->FinalJson(5,array());
            }
        }
        else
        {
            return $this->FinalJson($tokenData['errcode']);
        }
        $gamesCom = new GamesComplain();
        $gamesCom->setUserId($this->getUser());
        $gamesCom->setComplainDesc($param['com']);
        $this->_em()->persist($gamesCom);
        $this->_em()->flush($gamesCom);
        return $this->FinalJson(0);

    }

    /**
     * 用户保险柜记录
     *
     * @ApiDoc(
     *  resource=true,
     *  description="用户保险柜记录",
     *  parameters={
     *      {"name"="userToken", "dataType"="string","required"=true, "description"="用户token"},
     *  },
     * )
     * @Rest\POST("/user/safelog")
     */
    public function safelogAction(Request $request)
    {
        $param['userToken'] = $request->request->get('userToken','');
        $tokenData = $this->checkToken($param['userToken']);
        if(isset($tokenData['code']) && $tokenData['code'] == 1)
        {
            $userInfo = $tokenData['userinfo'] ? $tokenData['userinfo'] : array();
            if(!isset($userInfo['userId']) || empty($userInfo['userId']))
            {
                return $this->FinalJson(5,array());
            }
            $userId = $userInfo['userId'];
        }
        else
        {
            return $this->FinalJson($tokenData['errcode']);
        }
        $scoreLog = $this->_em()->getRepository('GamesBundle:UserScoreTopUpLog')->getLogList($userId);

        return $this->FinalJson(0,$scoreLog);
    }

    /**
     * 用户消费记录
     *
     * @ApiDoc(
     *  resource=true,
     *  description="用户消费记录",
     *  parameters={
     *      {"name"="userToken", "dataType"="string","required"=true,"description"="用户token"},
     *  },
     * )
     * @Rest\POST("/user/expense")
     */
    public function expenseAction(Request $request)
    {
        $param['userToken'] = $request->request->get('userToken','');
        $tokenData = $this->checkToken($param['userToken']);
        if(isset($tokenData['code']) && $tokenData['code'] == 1)
        {
            $userInfo = $tokenData['userinfo'] ? $tokenData['userinfo'] : array();
            if(!isset($userInfo['userId']) || empty($userInfo['userId']))
            {
                return $this->FinalJson(5,array());
            }
            $userId = $userInfo['userId'];
        }
        else
        {
            return $this->FinalJson($tokenData['errcode']);
        }
        $scoreLog = $this->_em()->getRepository('GamesBundle:UserScoreLog')->getLogList(6);
        return $this->FinalJson(0,$scoreLog);
    }

    /**
     * 发送短信
     *
     * @ApiDoc(
     *  resource=true,
     *  description="发送短信",
     *  parameters={
     *      {"name"="phone", "dataType"="string","required"=true,"description"="手机号码"},
     *  },
     * )
     * @Rest\POST("/sendcode")
     */
    public function sendcodeAction(Request $request)
    {
        $param['phone'] = $request->request->get('phone','');
        if (!preg_match("/^13[0-9]{1}[0-9]{8}$|15[0189]{1}[0-9]{8}$|189[0-9]{8}$/", $param['phone'])) {
            return $this->FinalJson(1);
        }
        $sms = $this->container->get('games_sms');
        $result = $sms->sendCode($param['phone']);
        return $this->FinalJson($result['code'],$result['sms_code']);
    }
}
